package com.example.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONObject;

import java.io.*;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {

    public HelloServlet() {
        super();
        message += "000";
    }

    private String message = "";

    public void init() {
        message += "Hello World!111";


    }

    public static int i = 0;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        i++;
        out.println("<h1>访问了" + i + "次</h1>");
        out.println("</body></html>");

        check("/", out);
    }

    private void check(String s, PrintWriter out) {

        Set<String> list = getServletContext().getResourcePaths(s);

        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {
                out.println(s);

                if (s.contains(".")) {

                    InputStream inputStream = getServletContext().getResourceAsStream(s);

                    String result = new BufferedReader(new InputStreamReader(inputStream))
                            .lines().collect(Collectors.joining(System.lineSeparator()));

                    out.println(result);
                } else {
                    check(s, out);
                }
            }
        };
        list.forEach(consumer);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        PrintWriter out = resp.getWriter();

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("a", "b");

        out.println(jsonObject);
    }

    public void destroy() {
    }
}
